package com.swsc.ai.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @describe:
 * @author: 容若
 * @created: 2024-08-08 14:41
 */
@RestController
@RequestMapping("/files")
public class FileController {
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file,
                                             @RequestParam("uuid") String uuid,
                                             @RequestParam("path") String loadPath,
                                             @RequestParam("fileName") String fileName,
                                             @RequestHeader("X-Auth-Token") String token) {
        if (StringUtils.hasLength(token)) {
            System.out.println("token：" + token);
        }
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择一个文件上传");
        }
        System.out.println(uuid);
        System.out.println("存储路径："+ loadPath + "/" + fileName);
        try {
            if (!Files.exists(Paths.get(loadPath))) {
                Files.createDirectories(Paths.get(loadPath));
            }
            byte[] bytes = file.getBytes();
            System.out.println("文件大小："+ bytes.length);
            File loadFile = new File(loadPath + "/" + fileName);
            Path path = loadFile.toPath();
            Files.write(path, bytes);
            return ResponseEntity.ok("文件上传成功：" + loadPath + "/" + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("文件上传失败：" + e.getMessage());
        }
    }
}
